package ph.com.gs3.formalistics.view.dialogs;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.formalistics.global.interfaces.CallbackCommand;
import ph.com.gs3.formalistics.model.valueobjects.business.document.DocumentAction;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

public class DocumentActionsDialogFragment extends DialogFragment {

	public static final String TAG = DocumentActionsDialogFragment.class.getSimpleName();

	private CallbackCommand<DocumentAction> onActionSelectedCallback;
	private List<DocumentAction> actions;

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {

		AlertDialog.Builder builder;

		if (actions == null || actions.isEmpty()) {
			builder = createEmptyActionsDialog();
		} else {
			builder = createActionsDialog();
		}

		return builder.create();

	}

	private AlertDialog.Builder createEmptyActionsDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

		builder.setTitle("Sorry").setMessage("No are actions available for this document")
		        .setNegativeButton("OK", null);

		return builder;

	}

	private AlertDialog.Builder createActionsDialog() {

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

		List<String> actionLabelList = createActionLabelList(actions);
		String[] actionsString = actionLabelList.toArray(new String[actionLabelList.size()]);
		builder.setTitle("Actions").setItems(actionsString, new OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if (onActionSelectedCallback != null) {
					onActionSelectedCallback.execute(actions.get(which));
				}
			}
		});

		return builder;

	}

	// ===================================================================================
	// Utility Methods

	private List<String> createActionLabelList(List<DocumentAction> actions) {

		List<String> labelList = new ArrayList<String>();

		for (DocumentAction action : actions) {
			labelList.add(action.getLabel());
		}

		return labelList;

	}

	// ===================================================================================
	// Getters & Setters

	public CallbackCommand<DocumentAction> getOnActionSelectedCallback() {
		return onActionSelectedCallback;
	}

	public void setOnActionSelectedCallback(CallbackCommand<DocumentAction> onActionSelectedCallback) {
		this.onActionSelectedCallback = onActionSelectedCallback;
	}

	public List<DocumentAction> getActions() {
		return actions;
	}

	public void setActions(List<DocumentAction> actions) {
		this.actions = actions;
	}

}
